package com.linxianqin.springbootVue.manage.core;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.linxianqin.springbootVue.domain.model.AjaxResult;
import com.linxianqin.springbootVue.domain.constant.HttpStatus;
import com.linxianqin.springbootVue.domain.page.TableDataInfo;
import com.linxianqin.springbootVue.domain.page.TableSupport;
import com.linxianqin.springbootVue.utils.DateUtils;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;


/**
 * 功能描述：web层通用数据处理
 * @author lxq
 * @version 1.00
 * @Date 2020/12/13
 */
@Slf4j
public class BaseController
{
    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected <T> Page<T> buildPage(){
        return TableSupport.buildPageRequest();
    }
    /**
     * 响应请求分页数据
     */
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
    /**
     * 响应请求分页数据
     */
    protected TableDataInfo getDataTable(Page<?> page)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getRecords());
        rspData.setTotal(page.getTotal());
        return rspData;
    }
    /**
     * 响应返回结果
     * 
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    protected AjaxResult toAjax(boolean b)
    {
        return b ? AjaxResult.success() : AjaxResult.error();
    }
    /**
     * 页面跳转
     */
    public String redirect(String url)
    {
        return StringUtils.format("redirect:{}", url);
    }
}
